<template>
  <div class="contract-template-page">
    <!-- 顶部导航 -->
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item @click="goHome">首页</el-breadcrumb-item>
        <el-breadcrumb-item @click="goToTemplates">合同模板</el-breadcrumb-item>
      </el-breadcrumb>
      <h1 class="template-title">合同模板库</h1>
    </div>

    <div class="page-content">
      <!-- 左侧分类 -->
      <div class="left-sidebar">
        <div class="category-section">
          <h3>合同分类</h3>
          <el-tree
            :data="categories"
            :props="categoryProps"
            default-expand-all
            @node-click="handleCategoryClick"
          />
        </div>
      </div>

      <!-- 右侧内容 -->
      <div class="right-content">
        <!-- 模板网格展示 -->
        <div class="template-grid">
          <div 
            v-for="template in templateList" 
            :key="template.id"
            class="template-card"
            @click="showTemplateDetail(template)"
          >
            <div class="template-image">
              <img :src="template.image" :alt="template.title" />
              <div class="template-overlay">
                <el-button type="primary" size="small" @click.stop="useTemplate(template)">
                  使用模板
                </el-button>
              </div>
            </div>
            <div class="template-info">
              <h4 class="template-title">{{ template.title }}</h4>
              <div class="template-meta">
                <span class="download-count">
                  <el-icon><Download /></el-icon>
                  {{ template.downloadCount }}
                </span>
                <span class="template-type">{{ template.type }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 模板详情对话框 -->
    <el-dialog
      v-model="templateDetailVisible"
      :title="selectedTemplate?.title"
      width="800px"
      class="template-detail-dialog"
    >
      <div class="template-detail-content">
        <div class="template-preview">
          <div class="preview-header">
            <h3>{{ selectedTemplate?.title }}</h3>
            <el-button type="primary" @click="downloadTemplate(selectedTemplate)">
              <el-icon><Download /></el-icon>
              下载模板
            </el-button>
          </div>
          <div class="word-content">
            <div class="word-document">
              <!-- 合同标题 -->
              <div class="document-title">
                <h2>{{ selectedTemplate?.title }}</h2>
              </div>
              
              <!-- 合同双方 -->
              <div class="document-parties">
                <p>甲方（{{ selectedTemplate?.parties?.partyA }}）：________________</p>
                <p>乙方（{{ selectedTemplate?.parties?.partyB }}）：________________</p>
              </div>

              <!-- 合同内容 -->
              <div 
                v-for="(section, index) in selectedTemplate?.content" 
                :key="index"
                class="document-section"
              >
                <h4>{{ section.title }}</h4>
                <div 
                  v-for="(item, itemIndex) in section.items" 
                  :key="itemIndex"
                  class="document-item"
                >
                  {{ item }}
                </div>
              </div>

              <!-- 签名区域 -->
              <div class="document-signature">
                <div class="signature-party">
                  <p>甲方（盖章）：</p>
                  <p>代表签字：________________</p>
                  <p>日期：________________</p>
                </div>
                <div class="signature-party">
                  <p>乙方（盖章）：</p>
                  <p>代表签字：________________</p>
                  <p>日期：________________</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 使用模板对话框 -->
    <el-dialog
      v-model="useTemplateDialogVisible"
      title="使用合同模板"
      width="600px"
    >
      <div class="use-template-form">
        <el-form :model="useForm" label-width="100px">
          <el-form-item label="合同编号">
            <el-input v-model="useForm.contractNumber" placeholder="请输入合同编号" />
          </el-form-item>
                    <el-form-item label="合同名称">
            <el-input v-model="useForm.contractName" placeholder="请输入合同名称" />
          </el-form-item>
        </el-form>
        <div style="text-align: right; margin-top: 20px;">
          <el-button @click="useTemplateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUseTemplate">确认使用</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  View,
  Download,
  Star,
  DocumentAdd
} from '@element-plus/icons-vue'

// 模板列表数据
const templateList = ref([
 {
  id: 1,
  title: '服务合同模板',
  type: '服务合同',
  image: new URL('@/assets/template/service.png', import.meta.url).href,
  downloadCount: 756,
  parties: {
    partyA: '委托方',
    partyB: '服务方'
  },
  content: [
    {
      title: '一、服务内容',
      items: [
        '1. 服务项目：________________',
        '2. 服务范围：________________',
        '3. 服务标准：________________',
        '4. 服务期限：________________'
      ]
    },
    {
      title: '二、服务费用',
      items: [
        '1. 服务费用总额：________________',
        '2. 支付方式：________________',
        '3. 支付时间：________________',
        '4. 发票要求：________________'
      ]
    },
    {
      title: '三、双方权利义务',
      items: [
        '1. 甲方应提供必要的配合和支持',
        '2. 乙方应按照约定标准提供服务',
        '3. 双方应保守对方的商业秘密',
        '4. 乙方应按时提交服务成果'
      ]
    }
  ]
},
  {
    id: 2,
    title: '房屋租赁合同模板',
    type: '租赁合同',
    image: new URL('@/assets/template/rental.png',import.meta.url).href,
    downloadCount: 1420,
    // 文件路径
    filePath: '/template/rentalword.docx',
    fileName: '厂房租赁合同模板.docx',
    fileSize: '45.2KB',
    parties: {
      partyA: '出租方',
      partyB: '承租方'
    },
    content: [
      {
        title: '一、租赁信息',
        items: [
          '1. 房屋地址：________________',
          '2. 租赁面积：________________',
          '3. 租赁期限：________________',
          '4. 租金标准：________________'
        ]
      },
      {
        title: '二、权利义务',
        items: [
          '1. 甲方保证房屋权属清晰',
          '2. 乙方按时支付租金',
          '3. 双方共同维护房屋设施'
        ]
      }
    ]
  },
  {
    id: 3,
    title: '技术服务合同模板',
    type: '服务合同',
    image: 'https://via.placeholder.com/200x150/E6A23C/ffffff?text=服务合同',
    downloadCount: 756,
    parties: {
      partyA: '委托方',
      partyB: '服务方'
    },
    content: [
      {
        title: '一、服务内容',
        items: [
          '1. 服务项目：________________',
          '2. 服务标准：________________',
          '3. 完成时限：________________'
        ]
      }
    ]
  },
  {
    id: 4,
    title: '劳动合同模板',
    type: '劳动合同',
    image: 'https://via.placeholder.com/200x150/F56C6C/ffffff?text=劳动合同',
    downloadCount: 2310,
    parties: {
      partyA: '用人单位',
      partyB: '劳动者'
    },
    content: [
      {
        title: '一、劳动合同期限',
        items: [
          '1. 合同期限：________________',
          '2. 试用期：________________'
        ]
      }
    ]
  },
  {
    id: 5,
    title: '合作协议模板',
    type: '合作协议',
    image: 'https://via.placeholder.com/200x150/909399/ffffff?text=合作协议',
    downloadCount: 543,
    parties: {
      partyA: '合作方A',
      partyB: '合作方B'
    },
    content: [
      {
        title: '一、合作内容',
        items: [
          '1. 合作项目：________________',
          '2. 合作方式：________________'
        ]
      }
    ]
  },
  {
    id: 6,
    title: '采购合同模板',
    type: '采购合同',
    image: 'https://via.placeholder.com/200x150/409EFF/ffffff?text=采购合同',
    downloadCount: 987,
    parties: {
      partyA: '采购方',
      partyB: '供应方'
    },
    content: [
      {
        title: '一、采购内容',
        items: [
          '1. 商品名称：________________',
          '2. 规格型号：________________'
        ]
      }
    ]
  }
])

const categories = ref([
  {
    label: '租赁合同',
    children: [
      { label: '房屋租赁合同' },
      { label: '设备租赁合同' },
      { label: '车辆租赁合同' }
    ]
  },
  {
    label: '服务合同',
    children: [
      { label: '技术服务合同' },
      { label: '咨询服务合同' },
      { label: '维护服务合同' }
    ]
  },
    {
    label: '购销合同',
    children: [
      { label: '产品购销合同' },
      { label: '设备购销合同' },
      { label: '材料购销合同' }
    ]
  },
])

const categoryProps = {
  children: 'children',
  label: 'label'
}

const templateDetailVisible = ref(false)
const selectedTemplate = ref(null)
const useTemplateDialogVisible = ref(false)
const useForm = ref({
  contractName: '',
  contractNumber: ''

})

// 方法
const handleCategoryClick = (data) => {
 
}

const viewTemplate = (item) => {

}

// 显示模板详情
const showTemplateDetail = (template) => {
  selectedTemplate.value = template
  templateDetailVisible.value = true
}

// 使用模板
const useTemplate = (template) => {
  selectedTemplate.value = template
  useTemplateDialogVisible.value = true
}

// 下载模板
const downloadTemplate = (template) => {
//   if (!template || !template.filePath) {
//     ElMessage.error('文档路径不存在')
//     return
//   }

//   try {
//     // 创建下载链接
//     const link = document.createElement('a')
//     link.href = template.filePath
//     link.download = template.fileName || '合同模板.docx'
//     link.target = '_blank'
    
//     // 触发下载
//     document.body.appendChild(link)
//     link.click()
//     document.body.removeChild(link)
    
//     // 更新下载计数
//     template.downloadCount++
//     ElMessage.success('文档下载成功')
    
//   } catch (error) {
//     console.error('下载失败:', error)
//     ElMessage.error('文档下载失败，请重试')
//   }
}

const handleUseTemplate = () => {
  if (!useForm.value.contractNumber) {
    ElMessage.error('请输入合同编号')
    return
  }
  if (!useForm.value.contractName) {
    ElMessage.error('请输入合同名称')
    return
  }
  useTemplateDialogVisible.value = false
  
  // 重置表单
  useForm.value.contractName = ''
  useForm.value.description = ''
  useForm.value.contractNumber = 'CT' + new Date().getTime().toString().slice(-8)
}

const goHome = () => {
  ElMessage.info('返回首页')
}

const goToTemplates = () => {
  ElMessage.info('返回模板列表')
}

onMounted(() => {
  ElMessage.success('页面加载完成')
})
</script>

<style scoped>
.contract-template-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.template-title {
  margin: 10px 0;
  color: #303133;
}

.page-content {
  display: flex;
  gap: 20px;
}

.left-sidebar {
  width: 250px;
  flex-shrink: 0;
}

.category-section {
  background: white;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.category-section h3 {
  margin-bottom: 15px;
  color: #303133;
}

.right-content {
  flex: 1;
}

/* 模板网格布局 */
.template-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.template-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;
}

.template-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.template-image {
  position: relative;
  height: 150px;
  overflow: hidden;
}

.template-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.template-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.template-card:hover .template-overlay {
  opacity: 1;
}

.template-info {
  padding: 12px;
}

.template-info .template-title {
  font-size: 14px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #303133;
  line-height: 1.4;
}

.template-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.download-count {
  display: flex;
  align-items: center;
  gap: 4px;
}

.template-type {
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 11px;
}

.use-template-form {
  padding: 10px;
}

@media (max-width: 768px) {
  .page-content {
    flex-direction: column;
  }
  
  .left-sidebar {
    width: 100%;
  }
  
  .template-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 15px;
    padding: 15px;
  }
}
</style>